﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using GameUI;
using Models;

namespace TBSGSVN
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            World world = CreateWorld();

            GameWindow gameWin = null;
            Thread gameWinThread = new Thread(() =>
            {
                gameWin = new GameWindow();
                //don't think I need these..
                //Application.EnableVisualStyles();
                //Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(gameWin);
            });

            gameWinThread.Start();

            //wait for the game window to load
            while (gameWin == null || !gameWin.Visible) ;

            //Start game timer
            GameTimer timer = new GameTimer(world, 500);
            timer.UpdateEvent += world.Update;
            timer.RenderEvent += gameWin.Render;

            //debug
              //  timer.UpdateEvent += (gameTimer) => { gameWin.SendCommand("update #" + gameTimer.GameTotalTicks); Console.WriteLine("tick"); };
            //end debug

            timer.Start();

            AcceptCommandLoop(gameWin);
        }

        private static World CreateWorld()
        {
            World world = new World(20, 20);
            return world;
        }

        private static void AcceptCommandLoop(GameWindow gameWin)
        {
            string command = "";
            while (! ConsoleCommands.Contains(command, ConsoleCommands.CLOSE))
            {
                command = Console.ReadLine();

                if (gameWin.CurrentState == GameWindow.State.CLOSED)
                {
                    //exit this loop
                    command = ConsoleCommands.CLOSE[0];
                }
                else if (gameWin.CurrentState == GameWindow.State.READY)
                {
                    gameWin.SendCommand(command);
                }
            }

            if (gameWin != null && gameWin.CurrentState != GameWindow.State.CLOSED)
            {
                gameWin.Invoke(new Action(() =>
                {
                    gameWin.Dispose();
                }));
            }
        }
    }
}
